package com.hsy.sunflowerbao.base.ui.activity

import android.os.Bundle
import android.support.annotation.NonNull

import com.flux.action.RxStoreChange
import com.flux.dispatcher.RxViewDispatch

import com.flux.ui.activity.FBaseActivity
import com.flux.utils.LogUtil
import com.gyf.barlibrary.ImmersionBar
import com.hsy.sunflowerbao.Application
import com.hsy.sunflowerbao.R
import com.hsy.sunflowerbao.base.store.BaseStore
import com.hsy.sunflowerbao.utils.CommonUtils

/**
 * 基础Activity
 * Created on 2017/12/4.
 *
 * @author Yang
 */
abstract class BaseActivity<T : BaseStore> : FBaseActivity(), RxViewDispatch {

    /**
     * 事件分发器
     */
    protected val dispatcher = Application.instance.rxFlux.dispatcher
    protected val manager = Application.instance.rxFlux.subscriptionManager
    @Suppress("UNCHECKED_CAST")
    protected abstract var store: T

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStatusBar()
        store.register()
        dispatcher.subscribeRxView(this)
    }

    /**
     * 设置状态栏颜色
     */
    protected open fun setStatusBar() {
        ImmersionBar.with(this)
                .statusBarColor(R.color.colorPrimary)//设置状态栏颜色
                .statusBarDarkFont(false)//设置状态栏文字颜色
                .init()
    }

    override fun onStop() {
        super.onStop()
        store.handleSuper = false
        CommonUtils.hideProgressDialog()
    }

    override fun onStart() {
        super.onStart()
        store.handleSuper = true
    }

    override fun onDestroy() {
        super.onDestroy()
        System.gc()

        unSubscribeDispatcher()
    }

    private fun unSubscribeDispatcher() {
        store.unregister()
        dispatcher.unsubscribeRxView(this)
    }

    /**
     * startActivity
     *
     * @param cls    目标类
     * @param extras 附加参数
     */
    override fun startActivityWithTaskCleared(cls: Class<*>, vararg extras: String) {
        unSubscribeDispatcher()
        super.startActivityWithTaskCleared(cls, *extras)
    }

    /**
     * 网络请求失败处理
     * @param change 数据变动
     */
    override fun onRxStoreChanged(@NonNull change: RxStoreChange) {
        if (store.handleSuper && change.storeId == BaseStore.ID) {
            val msg = if (store.msgRes != -1) getString(store.msgRes)
            else store.msg
            LogUtil.e("Http Error: $msg")
            if (store.needReLogin) {
                CommonUtils.showAuthFailureDialog(this, msg)
            } else {
                showToast(msg)
            }
        }
    }

    override fun getRxTag(): String {
        return javaClass.simpleName
    }
}